﻿using System;
using System.Linq;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using OAuthApp.Data;
using OAuthApp.Services;
using Swashbuckle.AspNetCore.Annotations;

namespace OAuthApp.Apis
{
    [SwaggerTag("应用聊天室")]
    [ServiceFilter(typeof(ApiRequestLoggingAttribute))]
    public class AppChatMessagesController : BaseController
    {
        private readonly AppDbContext _context;

        public AppChatMessagesController(AppDbContext context)
        {
            _context = context;
        }

        string ChatMessageTableName
        {
            get
            {
                return "_AppChatMessage_" + Request.RouteValues["appId"].ToString();
            }
        }

        #region 激活聊天室
        /// <summary>
        /// 激活聊天室
        /// </summary>
        /// <param name="appID"></param>
        /// <returns></returns>
        [HttpPost("{appId}/Active")]
        [SwaggerOperation(OperationId = "AppChatMessageActive")]
        public IActionResult Active()
        {
            var tName = _context.QueryFirstOrDefault<string>(
                "select name from sqlite_master WHERE TYPE = 'table' AND tbl_name = '" + ChatMessageTableName + "'");

            if (string.IsNullOrWhiteSpace(tName))
            {
                _context.Execute("CREATE TABLE " + ChatMessageTableName + "(" +
                                "ID          INTEGER  NOT NULL PRIMARY KEY AUTOINCREMENT," +
                                "Avatar      TEXT," +
                                "Content     TEXT," +
                                "CreateDate  DATETIME NOT NULL, " +
                                "GroupName   TEXT,              " +
                                "IsDelete    BOOLEAN  NOT NULL, " +
                                "LastUpdate  DATETIME NOT NULL, " +
                                "MessageType TEXT,              " +
                                "NickName    TEXT,              " +
                                "Platform    TEXT,              " +
                                "Remark      TEXT,              " +
                                "ShowIndex   INTEGER  NOT NULL, " +
                                "Tags        TEXT,              " +
                                "UnionID     TEXT               " +
                            ");");
            }

            return Ok(true);
        }
        #endregion

        #region 是否激活聊天室
        /// <summary>
        /// 是否激活聊天室
        /// </summary>
        /// <param name="appID"></param>
        /// <returns></returns>
        [HttpGet("{appId}/IsActived")]
        [SwaggerOperation(OperationId = "AppChatMessageIsActived")]
        public IActionResult IsActived()
        {
            var tName = _context.QueryFirstOrDefault<string>(
                "select name from sqlite_master WHERE TYPE = 'table' AND tbl_name = '" + ChatMessageTableName + "'");

            var result = string.IsNullOrWhiteSpace(tName);

            return Ok(result);
        }
        #endregion

        [HttpGet("{appId}")]
        [SwaggerOperation(OperationId = "AppChatMessages")]
        public ActionResult List(long appId,int skip, int take)
        {
            var result = _context.AppChatMessages
                //.Where(x => x.AppID == appId)
                .Skip(skip)
                .Take(take)
                .OrderByDescending(x => x.ID)
                .ToList();

            return OK(result);
        }

        [HttpGet("{appId}/{id}")]
        [SwaggerOperation(OperationId = "AppChatMessage")]
        public ActionResult Get(long id)
        {
            var result = _context.AppChatMessages.Find(id);

            if (result == null)
            {
                return Error("消息不存在");
            }

            return OK(result);
        }

        [HttpPut("{appId}/{id}")]
        [SwaggerOperation(OperationId = "AppChatMessagePut")]
        public ActionResult Put(AppChatMessage appChatMessage)
        {
            _context.Entry(appChatMessage).State = EntityState.Modified;

            try
            {
                _context.SaveChanges();
            }
            catch (Exception ex)
            {
                return Error(ex.Message);
            }

            return OK(true);
        }

        [HttpPost("{appId}")]
        [SwaggerOperation(OperationId = "AppChatMessagePost")]
        public ActionResult Post(AppChatMessage appChatMessage)
        {
            _context.AppChatMessages.Add(appChatMessage);

            _context.SaveChanges();

            return OK(new { id = appChatMessage.ID });
        }

        [HttpDelete("{appId}/{id}")]
        [SwaggerOperation(OperationId = "AppChatMessageDelete")]
        public ActionResult Delete(long id)
        {
            var result = _context.AppChatMessages.Find(id);

            if (result == null)
            {
                return Error("不存在的消息");
            }

            _context.AppChatMessages.Remove(result);

            _context.SaveChanges();

            return OK(true);
        }
    }
}
